use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{fmt::time::ChronoLocal, Layer, layer::SubscriberExt, Registry, util::SubscriberInitExt};

use crate::config::app_config::CONFIG;

pub fn config_tracing() -> anyhow::Result<()> {
    let log_config = &CONFIG.log;


    let timer = ChronoLocal::new("%Y-%m-%d %H:%M:%S%.3f".to_string());

    let (console_appender, _guard) = tracing_appender::non_blocking(std::io::stdout());
    let console_subscriber = tracing_subscriber::fmt::layer()
        .with_writer(console_appender)
        .with_timer(timer.clone())
        .with_level(true)
        .with_ansi(true);

    let file = tracing_appender::rolling::hourly(&log_config.path, &log_config.name);
    let (file_appender, _guard) = tracing_appender::non_blocking(file);

    let file_subscriber = tracing_subscriber::fmt::layer()
        .with_writer(file_appender)
        .with_timer(timer.clone())
        .with_level(true)
        .with_ansi(true);

    let subscriber = tracing_subscriber::registry()
        .with(console_subscriber)
        .with(file_subscriber);

    tracing::subscriber::set_global_default(subscriber)?;
    Ok(())
}

pub fn config_tracing_log() -> anyhow::Result<(WorkerGuard, WorkerGuard)> {
    let log_config = &CONFIG.log;
    let timer = ChronoLocal::new("%Y-%m-%d %H:%M:%S%.3f".to_string());

    let (console_appender, guard1) = tracing_appender::non_blocking(std::io::stdout());

    let fmt_layer = tracing_subscriber::fmt::layer()

        .with_timer(timer.clone())
        .with_target(true)
        .with_writer(console_appender)
        .with_ansi(true)
        .json()
        .with_filter(tracing_subscriber::filter::LevelFilter::DEBUG);

    let file_appender = tracing_appender::rolling::daily(&log_config.path, &log_config.name);

    let (no_blocking, guard) = tracing_appender::non_blocking(file_appender);
    let file_layer = tracing_subscriber::fmt::layer()
        .with_timer(timer)
        .with_target(true)
        .with_ansi(true)
        .with_writer(no_blocking)
        .json()
        .with_filter(tracing_subscriber::filter::LevelFilter::DEBUG);

    // let subscriber = tracing_subscriber::registry()
    // .with(fmt_layer)
    // .with(file_layer);

    // tracing::subscriber::set_global_default(subscriber)?;

    Registry::default().with(fmt_layer).with(file_layer).init();

    Ok((guard1, guard))
}
